package com.ywb.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ywb.entity.EduSubject;
import com.ywb.entity.excel.SubjectData;
import com.ywb.entity.subject.FirstSubject;
import com.ywb.entity.subject.SecondSubject;
import com.ywb.mapper.EduSubjectMapper;
import com.ywb.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ywb.utils.SubjectExcelListener;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author ywb
 * @since 2021-05-27
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Override
    public void saveSubject(MultipartFile file, EduSubjectService subjectService) {
        try{
//            EasyExcel将根据file的is以subjectData为模型进行SubjectExcelListener监听处理
            EasyExcel.read(file.getInputStream(), SubjectData.class, new SubjectExcelListener(subjectService)).sheet().doRead();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public List<FirstSubject> getFirstSubjects() {
        //        查询所有parent_id为0的为一级分类结合
        List<EduSubject> parents = this.list(new QueryWrapper<EduSubject>().eq("parent_id", "0"));
//        查询所有parent_id不为0的为二分类集合
        List<EduSubject> children = this.list(new QueryWrapper<EduSubject>().ne("parent_id", "0"));

        List<FirstSubject> firstSubjects = new ArrayList<>();
        for(EduSubject parent : parents){
            FirstSubject firstSubject = new FirstSubject();
            BeanUtils.copyProperties(parent, firstSubject);
            List<SecondSubject> secondSubjects = new ArrayList<>();
            for(EduSubject child : children){
                if(child.getParentId().equals(parent.getId())) {
                    SecondSubject secondSubject = new SecondSubject();
                    BeanUtils.copyProperties(child, secondSubject);
                    secondSubjects.add(secondSubject);
                }
            }
            firstSubject.setChildren(secondSubjects);
            firstSubjects.add(firstSubject);
        }
        return firstSubjects;
    }

    @Override
    public List<EduSubject> getSecondSubjectById(String parentId) {
        return list(new QueryWrapper<EduSubject>().eq("parent_id", parentId));
    }
}
